﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using Microsoft.Extensions.Configuration;
using Umi.Crypto.Abstraction.Keys;
using Umi.Web.Metadatas.Attributes;

namespace Umi.Web.Crypto.HMacs
{
    [Service("HmacKeyCreator", Scoped = ServiceScoped.Single)]
    public class HMacKeyFactory : IKeyParameterCreator
    {
        private readonly IConfiguration _configuration;

        public HMacKeyFactory(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public KeyParameter Create(string key)
        {
            return new HMacKeyParameter(Convert.FromBase64String(key));
        }

        public KeyParameter RandomKey()
        {
            int length = _configuration.GetValue<int>("Secret:HMac:KeyLength");
            RandomNumberGenerator generator = RandomNumberGenerator.Create();
            byte[] key = new byte[length / 8];
            generator.GetBytes(key);
            return new HMacKeyParameter(key);
        }
    }

    public class HMacKeyParameter : KeyParameter
    {
        public byte[] Key { get; }

        public HMacKeyParameter(byte[] key)
        {
            Key = key;
        }

        public override string ToString()
        {
            return Convert.ToBase64String(Key);
        }
    }
}
